<?php

$this->LoadHelper('MemberHelper');
$MemberHelper = new MemberHelper();

$this->LoadHelper('OrderHelper');
$OrderHelper = new OrderHelper();

$this->LoadHelper('SettingHelper');
$SettingHelper = new SettingHelper();

$this->LoadHelper('MessageHelper');
$MessageHelper = new MessageHelper();

$this->LoadHelper('BankHelper');
$BankHelper = new BankHelper();

$model = $this->LoadModel('Public');

$member_info = $MemberHelper->getMember($this->UserConfig['Id']);
$audit_row = $model->getOneRow('setting_audit','*',array('`au_id` =?' => $member_info['u_auditlevel']));
$member_info['toplimit'] = $audit_row['au_ceiling'] * 10000;
$this->Assign('member_info', $member_info);
$this->LoadHelper('RoleHelper');
$RoleHelper = new RoleHelper();

$dp_code = $member_info['u_dpcode'];
$this->LoadResurces('oldapi/class.carloan');
$oldapi = new Carloan();

$sign = $oldapi->sign(array('code' => $dp_code));
$api_baseurl = OLD_SITE_URL . '/OrderDetails/index/?code=' . $dp_code . '&sign=' . $sign['sign'];
$where = array('`r_id` = ?' => $member_info['u_role']);
$role_info = $RoleHelper->roleRow($where);

if (empty($this->Param['option'])) {

    //待终审列表
    $ajax = $this->Param['ajax'];
    $page = isset($this->Param['page']) ? $this->Param['page'] : 1;
    $rp = isset($this->Param['rp']) ? $this->Param['rp'] : PAGE_SIZE;
    if ($ajax) {
        $where = array(
            '`o_status` IN(?)' => array('初审提交', '审核中'),
            '`o_layer_status` IN(?)' => array('审核中', '未审核'),
        );
        $where['`ot_type` = ?'] = '层级审核';
        //根据用户审核层级锁定审核范围的订单
        /*if ($member_info['u_auditlevel'] > 0) {
            $audit_level = $SettingHelper->auditLevel($member_info['u_auditlevel']);
            if (!empty($audit_level['last'])) {
                $where['`o_layer_aucode` = ?'] = $audit_level['last']['au_code'];
            } else {
                $where['`o_layer_aucode` = ?'] = '';
            }
        }*/
        if(empty($this->Param['o_keyword'])){
            if($member_info['u_auditlevel'] ==8 || $member_info['u_auditlevel'] == 0){
                if($this->Param['rt'] == 1024)
                    $where['`o_final_perch` =?'] = $member_info['u_id'];
                else
                    $where['`o_layer_status` IN(?)'] = array('审核中', '未审核');
            }elseif($member_info['u_auditlevel'] == 9){
                 $where['`o_final_perch` =?'] = $member_info['u_id'];
            }else{
                $where['`o_final_perch` IN (?)'] = array($member_info['u_id'], 0);
            }
        }else{
            $where['`o_layer_status` IN(?)'] = array('审核中', '未审核','暂停中');
        }

        $data = $OrderHelper->orderList($where, $page, $rp, $this->Param, $member_info, 'order_split', array("`o_audit_priority` DESC", "`o_first_time` ASC"));
        $json_data = array('total' => $data['count'], 'rows' => array());

        $mode = Config::GetCommon();
        if (!empty($data['all'])) {
            foreach ($data['all'] as $rowNum => $row) {
                $row['o_search_time'] = empty($row['o_search_time']) ? '' : date('Y-m-d H:i:s', $row['o_search_time']);
                $row['o_first_time'] = empty($row['o_first_time']) ? '' : date('Y-m-d H:i:s', $row['o_first_time']); //初审提交时间
                $row['o_first_atime'] = empty($row['o_first_atime']) ? '' : date('Y-m-d H:i:s', $row['o_first_atime']); //初审通过时间
                $row['o_finishs_time'] = empty($row['o_finishs_time']) ? '' : date('Y-m-d H:i:s', $row['o_finishs_time']); //终审提交时间
                $row['o_finishe_time'] = empty($row['o_finishe_time']) ? '' : date('Y-m-d H:i:s', $row['o_finishe_time']); //终审通过
                $row['o_telstart_time'] = empty($row['o_telstart_time']) ? '' : date('Y-m-d H:i:s', $row['o_telstart_time']); //电审开始时间
                $order_car = $OrderHelper->orderCar($row['o_id']);
                $row['ot_loan_limit'] = $order_car['ot_loan_limit']; //贷款金额
                $row['o_pre_modetext'] = $mode['mode'][$row['o_pre_mode']]['mode_text'];
                //
                $o_perch = $MemberHelper->getMemberRow($row['o_final_perch']);
                $row['o_perch_name'] = $o_perch['u_realname']; //占位人员

                $bank_row = $BankHelper->bankRow($row['o_bank_id']);
                $row['o_bank_abb'] = $bank_row['bk_abbreviation'];

                //
                if ($row['o_oldsys'] == 1) {
                    $sign = $oldapi->sign(array('code' => $dp_code));
                    $row['info_url'] = $api_baseurl . '&id=' . $row['o_number'];
                } else {
                    $row['info_url'] = '/index/index/option/info?oid=' . $row['o_id'];
                }
                $json_data['rows'][] = $row;
            }
        }
        echo json_encode($json_data);
    } else {
        echo $this->GetView('order_faolist.php');
    }
} else {
    switch ($this->Param['option']) {
        case 'faoinfo':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }

            $upcount=$OrderHelper->orderuping($oid,'终审');
            if($upcount>0){
                echo "<script>alert('当前订单有未处理的修改申请');</script>";
            }

            //占位判断
            $r_role_arr = unserialize($role_info["r_role"]);
            $result = $OrderHelper->fperchJudge($oid, $member_info, $r_role_arr);
            if (!$result['success']) {
                ErrorMsg::Debug($result['msg']);
            }
            $audit_level = $SettingHelper->auditLevel($member_info['u_auditlevel']);
            $order = $OrderHelper->orderInfo($oid);
            if($order['car']['ot_loan_limit'] <= 80000){
                $a_type = 'A00003终审审核';
            }else{
                if($member_info['toplimit'] < $order['car']['ot_loan_limit']){
                    $a_type = 'A00001终审审核';
                }else{
                    $a_type = 'A00003终审审核';
                }
            }
            $base_url = \yii2api\Config::$base_url;
            $uri = 'chedai/unionpay/orders-get3002';
            $body = array(
                "o_id" => $oid
            );
            $reponse = \Httpful\Request::post($base_url.$uri)->body($body)->sendsType(\Httpful\Mime::FORM)->send();
            $data =  $OrderHelper->object2array_pre($reponse->body->data);
            foreach($data as $k => $v){
                if($v['ct_code'] == $order['base']['buyer']['ct_code'] && $v['status_msg'] == '有相似度'){
                    $order['base']['buyer']['visa'] = $v['score'];
                }elseif(!empty($order['spouse']) && $v['ct_code'] == $order['spouse']['ct_code'] && $v['status_msg'] == '有相似度'){
                    $order['spouse']['visa'] = $v['score'];
                }elseif(!empty($order['guarantor'])){
                    foreach($order['guarantor'] as $x => $y){
                        if($v['ct_code'] == $y['ct_code'] && $v['status_msg'] == '有相似度'){
                             $order['guarantor'][$x]['visa'] = $v['score'];
                        }
                    }
                }
            }
            $order['audit_ok'] = $OrderHelper->orderAuditfilter($order['audit_all']['ok'], '初审审核');
            $order['audit_draft'] = $OrderHelper->orderAuditfilter($order['audit_all']['draft'],$a_type);
            $order['audit_type'] = $OrderHelper->getFinalresult($oid);
            $order['audit_front'] = $OrderHelper->orderAuditfilter($order['audit_all']['ok'], 'A00003终审审核');
            $order['idaddresscheck'] = $OrderHelper->idaddressCheck($oid);//身份证地址查重
            $order['contractdetails'] = $OrderHelper->contractDetails($oid);
            $order['phonecheck'] = $OrderHelper->phoneCheck($oid); //手机号查重
            $order['carmodelcheck'] = $OrderHelper->carmodelCheck($oid); //两个月内同车系排查
            $order['companycheck'] = $OrderHelper->companyCheck($oid);//同公司名查重
            $this->Assign('order', $order);
            echo $this->GetView('order_faoinfo.php');
            break;
        case 'save':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $save_type = empty($this->Param['savetype']) ? 'draft' : $this->Param['savetype'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }

            $upcount=$OrderHelper->orderuping($oid,'终审');
            if($upcount>0){
                if($this->Param['a_results']=='可以办理') {
                    ErrorMsg::Debug('当前订单有未处理的修改申请，请处理完毕再来通过！');
                }
            }
            if ($save_type == 'draft') {
                $this->Param['draft'] = true;
            } else {
                $this->Param['draft'] = false;
                if(isset($this->Param['o_web_risk'])){
                    if(empty($this->Param['a_details'])){
                        ErrorMsg::Debug('请选择通过类型！');
                    }
                }
            }
            $this->Param['a_uid'] = $this->UserConfig['Id'];
            $result = $OrderHelper->dataFinal($this->Param, $oid);
            if ($result['success']) {

                if($this->Param['a_results']=='不予办理'&& $save_type=='save'){
                    $result1 = $OrderHelper->orderupUpdate(array(
                        'up_status' => '作废'
                    ),'',$oid);
                }

                if ($save_type != 'draft') {
                    $MemberHelper->saveLog($this->UserConfig, '终审审核', json_encode($this->Param), $this->Controller . '_' . $this->Action);
                    //如果为终审通过 发送消息
                    if ($result['data']['flag']) {
                        $order_row = $OrderHelper->orderRow($oid);
                        $MessageHelper->sendSingle(array(
                            'm_uid' => $order_row['o_uid'],
                            'm_title' => '终审通过',
                            'm_name' => $order_row['o_uname'],
                            'm_content' => $order_row['o_vip_name'] . '终审通过',
                            'm_dateline' => NOW_TIME,
                            'm_oid' => $oid,
                            'm_info' => serialize(array('status' => '终审通过', 'code' => $OrderHelper->statusChange('终审通过'))),
                        ));
                    }
                    $suspendMsg = $OrderHelper->suspendMsg($oid);
                    if(!empty($suspendMsg))  $MessageHelper->sendSingle($suspendMsg);
                }

                ErrorMsg::Debug($save_type == 'draft' ? '保存成功' : '审核成功', true);
            } else {
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'back': //订单退回
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }

            $this->Assign('oid', $oid);
            echo $this->GetView('order_faoback.php');
            break;
        case 'backsave': //退回保存
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $status = empty($this->Param['status']) ? ErrorMsg::Debug('请选择退回状态') : $this->Param['status'];
            $remarks = $this->Param['remarks'];
            $v_type = 'faooprate';
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }
            $result = $OrderHelper->orderBack($oid, $status, $remarks, array('uid' => $this->UserConfig['Id'], 'uname' => $member_info['u_realname']), $v_type,$this->Param['lock_car']);
            if ($result['success']) {

                $result1 = $OrderHelper->orderupUpdate(array(
                    'up_status' => '作废'
                ),'',$oid);

                $MemberHelper->saveLog($this->UserConfig, '终审退回', json_encode($this->Param), $this->Controller . '_' . $this->Action);
                //发送消息
                $order_row = $OrderHelper->orderRow($oid);
                $MessageHelper->sendSingle(array(
                    'm_uid' => $order_row['o_uid'],
                    'm_title' => '终审退回',
                    'm_name' => $order_row['o_uname'],
                    'm_content' => $order_row['o_vip_name'] . '终审退回',
                    'm_dateline' => NOW_TIME,
                    'm_oid' => $oid,
                    'm_info' => serialize(array('status' => '终审退回', 'code' => $OrderHelper->statusChange('退回'))),
                ));
                ErrorMsg::Debug('保存成功', true);
            } else {
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'chkout': //订单签出
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }

            $result = $OrderHelper->orderChkout($oid, '终审', array('uid' => $this->UserConfig['Id'], 'uname' => $member_info['u_realname']));
            if ($result['success']) {
                $MemberHelper->saveLog($this->UserConfig, '终审签出', json_encode($this->Param), $this->Controller . '_' . $this->Action);
                ErrorMsg::Debug('保存成功', true);
            } else {
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'attach_remove':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $type = empty($this->Param['type']) ? ErrorMsg::Debug('面签资料类型错误') : $this->Param['type'];
            $fname = empty($this->Param['fname']) ? ErrorMsg::Debug('文件名错误') : $this->Param['fname'];
            $attachment_row = $OrderHelper->attachRow($oid);
            if (empty($attachment_row)) {
                ErrorMsg::Debug('未找到相关数据');
            }

            $data = unserialize($attachment_row[$type]);
            if (!in_array($fname, $data)) {
                ErrorMsg::Debug('不存在面签数据');
            }

            $re_data = array();
            foreach ($data as $k => $v) {
                if ($v !== $fname) {
                    $re_data[] = $v;
                }
            }
            $OrderHelper->attachUpdate(array($type => serialize($re_data)), $oid);
            ErrorMsg::Debug('删除成功', true);
            break;
        case 'suspend':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }
            $this->Assign('oid', $oid);
            echo $this->GetView('order_faosuspend.php');
            break;
        case 'suspendsave':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $remarks = $this->Param['remarks'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }
            $result = $OrderHelper->orderSuspend($oid, $remarks, array('uid' => $this->UserConfig['Id'], 'uname' => $member_info['u_realname']),'fao');
            if ($result['success']) {
                $MemberHelper->saveLog($this->UserConfig, '终审暂停', json_encode($this->Param), $this->Controller . '_' . $this->Action);
                $suspendMsg = $OrderHelper->suspendMsg($oid);
                if(!empty($suspendMsg))  $MessageHelper->sendSingle($suspendMsg);
                ErrorMsg::Debug('保存成功', true);
            } else {
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case'againsave':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $remarks = $this->Param['a_remarks'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if (!$order_check['success']) {
                ErrorMsg::Debug('无权操作');
            }
            $result = $OrderHelper->auditAgain($oid,$member_info,$remarks);
            if($result['success']){
                $MemberHelper->saveLog($this->UserConfig, '终审回退到上级审核员', json_encode($this->Param), $this->Controller . '_' . $this->Action);
                ErrorMsg::Debug('保存成功', true);
            } else {
                ErrorMsg::Debug($result['msg']);
            }

            break;
        case 'replace':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $member_arr = $OrderHelper->getSameLevelAuditor($oid);
            $this->Assign('member_arr', $member_arr);
            $this->Assign('oid', $oid);
            echo $this->GetView('order_faoreplace.php');
            break;
        case 'replacesave':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $o_final_perch = empty($this->Param['o_final_perch']) ? ErrorMsg::Debug('请选择审核人员') : $this->Param['o_final_perch'];
            $result = $OrderHelper->replaceTelAuditor($oid,$o_final_perch);
            if($result['success']){
                $MemberHelper->saveLog($this->UserConfig, '替换审核员', json_encode($this->Param), $this->Controller . '_' . $this->Action);
                ErrorMsg::Debug('替换成功', true);
            }else{
                ErrorMsg::Debug('替换失败');
            }
            break;
        default:
    }
}
